package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.mq.MqMessage;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponse;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.constant.PayConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.MqMessageService;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.to.SpuInfoVo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.databind.ObjectMapper;
import enume.OrderStatusEnum;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.atguigu.gulimall.order.constant.OrderConstant.USER_ORDER_TOKEN_PREFIX;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    //
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    MqMessageService mqMessageService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo getOrderConfirmVo() throws Exception {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberResponse member = LoginUserInterceptor.loginUser.get();
        // 多线程 不能在拦截器中回去request 要手动set
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 异步编排

        CompletableFuture<Void> memberFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            /** feign 会员收获地址列表 **/
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("member_id", member.getId());
            R info = memberFeignService.list(map);
            if (info.getCode() == 0) {
                Map<String, Object> objectMap = (Map<String, Object>) info.get("page");
                orderConfirmVo.setMemberAddressVos((List<MemberAddressVo>) objectMap.get("list"));
            }
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            /** feign 所有选中的购物项 **/
            R r = null;
            try {
                r = cartFeignService.getCheckedCartList();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (r.getCode() == 0) {
                List<OrderItemVo> data = (List<OrderItemVo>) r.getData("data", new TypeReference<List<OrderItemVo>>() {
                });
                orderConfirmVo.setItems(data);
            }
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIdList = items.stream().map(orderItemVo -> orderItemVo.getSkuId()).collect(Collectors.toList());
            R skuHasStock = wmsFeignService.getSkuHasStock(skuIdList);
            Map<Long, Boolean> stockMap = new HashMap<>();
            ;
            List<SkuHasStockVo> data = (List<SkuHasStockVo>) skuHasStock.get("data");
            for (Object item : data) {
                String jsonObject = JSON.toJSONString(item);
                //将json转成需要的对象
                SkuHasStockVo skuHasStockVo = JSONObject.parseObject(jsonObject, SkuHasStockVo.class);
                stockMap.put(skuHasStockVo.getSkuId(), skuHasStockVo.getHasStock());
            }
            orderConfirmVo.setStocks(stockMap);
        }, executor);


        /** 用户积分 **/
        Integer integration = member.getIntegration();
        orderConfirmVo.setIntegration(integration);

        // 其他计算


        //  token 防刷令牌
        String orderToken = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(USER_ORDER_TOKEN_PREFIX + member.getId(), orderToken, 5, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(orderToken);

        // 等待多有线程执行完成。
        CompletableFuture.allOf(memberFuture, cartFuture).get();

        return orderConfirmVo;
    }

    // 本地事务不满足
    // 了。 要使用分布式事务
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) throws Exception {
        // 线程共享 ，订单项信息
        confirmVoThreadLocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        // 1 验证令牌
        MemberResponse member = LoginUserInterceptor.loginUser.get();
        String orderToken = vo.getOrderToken();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

        //通过lure脚本原子验证令牌和删除令牌
        Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(USER_ORDER_TOKEN_PREFIX + member.getId()),
                orderToken);

        if (execute == 0L) {
            // 验证失败
            responseVo.setCode(1);
            return responseVo;
        } else {
            responseVo.setCode(0);
            // 验证成功 ， 继续操作
            OrderCreateTo order = createOrder();

            // 2\ . 验证价格
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            // 比较两个值 相差0.01内 则为 相等， 因为附浮点数 有误差0.007
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {

                // 保存订单
                saveOrder(order);

                // 库存 处理 , 重要地方 ， 只要锁定库存位置出现异常 ， 则回滚
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());

                // 要锁定的商品
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(orderItemVos);

                /**
                 *  重点 ：：：！！！！！！
                 *      使用RabbitMQ 实现分布式事务的最终一致性 ， 并发性能更好
                 *       使用RabbitMQ 实现分布式事务的最终一致性 ， 并发性能更好
                 *        使用RabbitMQ 实现分布式事务的最终一致性 ， 并发性能更好
                 */
                // todo  远程调用  锁库存
                try {
                    R r = wmsFeignService.orderLockStock(lockVo);
                    if (r.getCode() == 0) {
                        // 锁定成功
                        responseVo.setOrder(order.getOrder());

                        // todo 发消息给订单交换机，  定时去关闭
                        String uuid = UUID.randomUUID().toString().replace("-", "");
                        order.getOrder().setMqMessageId(uuid);
                        CorrelationData correlationData = new CorrelationData(uuid);

                        String jsonString = JSON.toJSONString(order.getOrder());
                        MqMessage mqMessage = new MqMessage();
                        mqMessage.setMessageId(uuid);
                        mqMessage.setMessageStatus(0);  // 新建
                        mqMessage.setContent(jsonString);
                        mqMessage.setRoutingKey("order.create.order");
                        mqMessage.setToExchange("order-event-exchange");
                        mqMessage.setClassType(OrderEntity.class.getTypeName());
                        mqMessage.setCreateTime(new Date());
                        mqMessage.setUpdateTime(new Date());
                        mqMessageService.save(mqMessage);

                        rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder(), correlationData);


                        return responseVo;
                    } else {
                        String msg = (String) r.get("msg");
                        throw new NoStockException(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    responseVo.setCode(3);
                    throw new NoStockException("远程库存未响应");
                }
            } else {
                responseVo.setCode(2);
            }
        }
        return responseVo;
    }





    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {

        OrderEntity orderSn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderEntity.getOrderSn()));
        if (orderSn != null && orderSn.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            // 幂等性， 只有待付款订单 才删除
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderSn, orderTo);
            // 发消息给mq  ， 去解锁库存
            try {

                // todo  每个发消息的地方 都要做好 日志表的记录 ， 防止消息丢失
                String uuid = UUID.randomUUID().toString().replace("-", "");
                orderTo.setMqMessageId(uuid);
                CorrelationData correlationData = new CorrelationData(uuid);


                String jsonString = JSON.toJSONString(orderTo);
                MqMessage mqMessage = new MqMessage();
                mqMessage.setMessageId(orderTo.getMqMessageId());
                mqMessage.setMessageStatus(0);  // 新建
                mqMessage.setContent(jsonString);
                mqMessage.setRoutingKey("order.release.other");
                mqMessage.setToExchange("order-event-exchange");
                mqMessage.setClassType(OrderTo.class.getTypeName());
                mqMessage.setCreateTime(new Date());
                mqMessage.setUpdateTime(new Date());
                mqMessageService.save(mqMessage);

                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo, correlationData);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity orderByOrderSn = this.getOrderByOrderSn(orderSn);
        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderSn);
        payVo.setTotal_amount(orderByOrderSn.getPayAmount().setScale(2,BigDecimal.ROUND_UP).toString());
        List<OrderItemEntity> orderItems = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        payVo.setSubject(orderItems.get(0).getSkuName());
        payVo.setBody(orderItems.get(0).getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponse memberResponseVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id",memberResponseVo.getId()).orderByDesc("create_time")
        );

        //遍历所有订单集合
        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            //根据订单号查询订单项里的数据
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", order.getOrderSn()));
            order.setOrderItemEntityList(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);

        return new PageUtils(page);

    }

    /**
     * 处理支付宝的支付结果
     * @param asyncVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String handlePayResult(PayAsyncVo asyncVo) throws ParseException {

        //保存交易流水信息
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(asyncVo.getBuyer_pay_amount()));
        paymentInfo.setSubject(asyncVo.getBody());
        paymentInfo.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfo.setCreateTime(new Date());

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = dateFormat.parse(asyncVo.getNotify_time());
        paymentInfo.setCallbackTime(date);
        //添加到数据库中
        this.paymentInfoService.save(paymentInfo);

        //修改订单状态
        //获取当前状态
        String tradeStatus = asyncVo.getTrade_status();

        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = asyncVo.getOut_trade_no(); //获取订单号
            this.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY);
        }

        return "success";
    }

    @Override
    @Transactional
    public void createSeckillOrderInfo(SeckillOrderTo orderTo) {
        //  保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = orderTo.getSeckillPrice().multiply(BigDecimal.valueOf(orderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //保存订单
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(orderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);
        orderItem.setSkuId(orderTo.getSkuId());
        orderItem.setSkuQuantity(orderTo.getNum());

        // todo  1
        // 保存商品的spu信息
        // 都是一样的逻辑，远程调用一下商品服务就可以了
        // .......


        // todo  2
        // 地址可以先使用用户的默认地址， 当抢购成功后，用户可以再进行修改地址信息
        // .....


        //保存订单项数据
        orderItemService.save(orderItem);
    }


    /**
     * 修改订单状态
     * @param orderSn
     * @param code
     */
    private void updateOrderStatus(String orderSn, Integer code,Integer payType) {

        this.baseMapper.updateOrderStatus(orderSn,code,payType);
    }

    private void saveOrder(OrderCreateTo orderCreateTo) {
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        this.baseMapper.insert(order);

        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() throws Exception {
        OrderCreateTo orderCreateTo = new OrderCreateTo();

        // 1. 生成订单
        String orderId = IdWorker.getTimeId();
        OrderEntity orderEntity = builderOrder(orderId);
//        orderCreateTo.setOrder(orderEntity);

        // 2、 获取所有订单
        List<OrderItemEntity> orderItemEntities = builderOrderItems(orderId);


        //3、验价(计算价格、积分等信息)
        computePrice(orderEntity, orderItemEntities);

        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);


        return orderCreateTo;
    }

    /**
     * 计算价格的方法
     *
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {

        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }

    /**
     * 构建所有订单项数据
     *
     * @return
     */
    private List<OrderItemEntity> builderOrderItems(String orderSn) throws Exception {
        List<OrderItemEntity> orderItemEntityList = new ArrayList<>();

        //最后确定每个购物项的价格
        R r = cartFeignService.getCheckedCartList();
        List<OrderItemVo> currentCartItems = (List<OrderItemVo>) r.getData("data", new TypeReference<List<OrderItemVo>>() {
        });
        if (currentCartItems != null && currentCartItems.size() > 0) {
            orderItemEntityList = currentCartItems.stream().map((item) -> {
                //构建订单项数据
                OrderItemEntity orderItemEntity = builderOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }

        return orderItemEntityList;
    }

    /**
     * 构建某一个订单项的数据
     *
     * @param item
     * @return
     */
    private OrderItemEntity builderOrderItem(OrderItemVo item) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、商品的spu信息
        Long skuId = item.getSkuId();
        //获取spu的信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = (SpuInfoVo) spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandName());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        //2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuPic(item.getImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        orderItemEntity.setSkuQuantity(item.getCount());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(item.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //3、商品的优惠信息  .....


        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
        orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());

        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());

        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

    /**
     * 构建订单数据
     *
     * @param orderSn
     * @return
     */
    private OrderEntity builderOrder(String orderSn) {
        MemberResponse memberResponseVo = LoginUserInterceptor.loginUser.get();

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(memberResponseVo.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberResponseVo.getUsername());

        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();

        //远程获取收货地址和运费信息
        R fareAddressVo = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = (FareVo) fareAddressVo.getData("data", new TypeReference<FareVo>() {
        });
        //获取到运费信息
        BigDecimal fare = fareResp.getFare();
        orderEntity.setFreightAmount(fare);

        //获取到收货地址信息
        MemberAddressVo address = fareResp.getAddress();
        //设置收货人信息
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());

        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);

        return orderEntity;
    }

}